import { ref, reactive, toRefs, getCurrentInstance, computed } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useStore } from "vuex";
import { useRouter, useRoute } from "vue-router";
import { PageVo, User, R } from "@api/model";
import { remove, getCurrentUser, update, save } from "@api/user";
import { uploadFile } from "@api/teacher";

const store = useStore();
interface UserForm {
    username: string;
    password: string;
    nickName?: string;
    //头像
    salt?: string;
}
export default function userFormR() {
    const userFormReactive = reactive<{ userForm: UserForm }>({
        /*
             为了给reactive对象赋值，需要将对象定义为其中的一个属性。
            */
        userForm: {
            username: "666",
            password: "666",
            nickName: "666",
            //头像
            salt: "",
        },
    });

    getCurrentUser().then((resp: R<User>) => {
        userFormReactive.userForm = resp.data;
    });


    // 获取当前组件实例对象
    const currentInstance = getCurrentInstance();
    function submit(event: MouseEvent) {
        (currentInstance?.refs.userFormRef as any).validate((valid: boolean) => {
            if (!valid) {
                return;
            }
            update(userFormReactive.userForm as User)
                .then((resp: any) => {
                    location.reload();
                    ElMessage.success(resp);
                });
        })
    }
    // 文件上传
    function cutDown(cutImage: { file: File }) {
        // 从解构的对象中获取文件传给上传api
        uploadFile([cutImage.file]).then(fileName => {
            // 成功回调就是图片的地址
            // 将地址保存的表单数据对象中，在表单提交数据时就已经有图片地址了
            userFormReactive.userForm.salt = fileName
            ElMessage.success("头像上传成功")
        })
    }
    return {
        cutDown,
        ...toRefs(userFormReactive),
        submit,
    };
}